package blog.service.impl;

import blog.common.Result;
import blog.entity.Message;
import blog.mapper.MessageMapper;
import blog.service.MessageService;
import blog.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jjpzh
 * @since 2023-02-25
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {


    @Override
    public Result listByPage(Integer page, Integer size) {
        Page<Message> messagePage = new Page<>(page, size);
        messagePage = page(messagePage, new LambdaQueryWrapper<Message>().orderByAsc(Message::getCreateTime));
        return Result.success(messagePage);
    }

    @Autowired
    private UserService userService;

    @Override
    @Async
    public void addMessage(String from, String to, String content) {
        if (StringUtils.isBlank(content)) {
            return;
        }
        Message message = new Message();
        message.setFromName(from);
        message.setToName(to);
        message.setContent(content);
        save(message);

    }

    @Override
    public Result listByTo(String to) {
        //根据to为to或all的消息
        return Result.success(list(new LambdaQueryWrapper<Message>().eq(Message::getToName, to).or().eq(Message::getToName, "all").orderByAsc(Message::getCreateTime)));
    }

    @Override
    public Result listByFrom(String from) {
        //根据from查询所有的消息
        return Result.success(list(new LambdaQueryWrapper<Message>().eq(Message::getFromName, from).orderByAsc(Message::getCreateTime)));
    }

    @Override
    public Result listByFromAndTo(String from, String to) {
        //根据from和to查询所有的消息,from和to都是用户名,两者可以交换
        return Result.success(list(new LambdaQueryWrapper<Message>().eq(Message::getFromName, from).eq(Message::getToName, to).or().eq(Message::getFromName, to).eq(Message::getToName, from).orderByAsc(Message::getCreateTime)));
    }

    @Override
    public Result listByToNameIsAll() {
        //查询toName为all的消息
        return Result.success(list(new LambdaQueryWrapper<Message>().eq(Message::getToName, "all").orderByAsc(Message::getCreateTime)));
    }


}
